package storage

import (
	"time"

	"github.com/redis/go-redis/v9"
	"go.mongodb.org/mongo-driver/v2/mongo"
	"go.mongodb.org/mongo-driver/v2/mongo/options"
)

type StorageConfig struct {
	MongoUrl      string
	MongoDataBase string
	RedisAddr     string
	RedisPasswd   string
}

type StorageHandle struct {
	TaskInfoDao       *_TaskInfoDao
	MessageInfoDao    *_MessageInfoDao
	ArtifactInfoDao   *_ArtifactInfoDao
	FormDefineInfoDao *_FormDefineInfoDao
	EventDao          *_EventDao
	FileDao           *_FileDao
}

func NewStorageHandle(cfg *StorageConfig) (*StorageHandle, error) {
	clientOpts := options.Client().ApplyURI(cfg.MongoUrl).SetConnectTimeout(10 * time.Second)
	client, err := mongo.Connect(clientOpts)
	if err != nil {
		return nil, err
	}
	db := client.Database(cfg.MongoDataBase)
	sh := &StorageHandle{}
	//int mongo dao
	sh.TaskInfoDao, err = newTaskInfoDao(db)
	if err != nil {
		return nil, err
	}
	sh.MessageInfoDao, err = newMessageInfoDao(db)
	if err != nil {
		return nil, err
	}
	sh.ArtifactInfoDao, err = newArtifactInfoDao(db)
	if err != nil {
		return nil, err
	}
	sh.FormDefineInfoDao, err = newFormDefineInfoDao(db)
	if err != nil {
		return nil, err
	}
	sh.FileDao, err = newFileDao(db)
	if err != nil {
		return nil, err
	}
	//init redis and notice dao
	rdb := redis.NewClient(&redis.Options{
		Addr:     cfg.RedisAddr,
		Password: cfg.RedisPasswd,
	})
	sh.EventDao = &_EventDao{
		client: rdb,
	}
	return sh, nil
}
